package com.dt.service;

import com.dt.dto.TextMessageDto;
import com.dt.utils.ReturnMsgUtil;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @Auther: dengtao
 * @Date: 2019/11/25 11:42
 * @Description:
 */
public class WebSocketService {

    private static ChannelGroup GlobalGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static ConcurrentMap<String, Channel> ChannelMap = new ConcurrentHashMap();

    private static ConcurrentMap<String,String> sendIdMap = new ConcurrentHashMap<>();

    public static void addChannel(TextMessageDto textMessageDto,Channel channel){
        GlobalGroup.add(channel);
        ChannelMap.put(textMessageDto.getSenderId(),channel);
        sendIdMap.put(channel.remoteAddress().toString(),textMessageDto.getSenderId());
    }

    public static void removeChannel(Channel channel){
        GlobalGroup.remove(channel);
        String sendId = sendIdMap.get(channel.remoteAddress().toString());
        ChannelMap.remove(sendId);
    }

    public static void removeChannelId(String id){
        Channel channel = ChannelMap.get(id);
        GlobalGroup.remove(channel);
        ChannelMap.remove(id);
    }

    public static Channel findChannel(String id){
        return ChannelMap.get(id);
    }

    public static void sendToMe(TextMessageDto textMessageDto,Channel channel) {
        channel.writeAndFlush(ReturnMsgUtil.returnMsg(textMessageDto));
    }

    public static void sendToOther(TextMessageDto textMessageDto){
        Channel channel = findChannel(textMessageDto.getReceiverId());
        channel.writeAndFlush(ReturnMsgUtil.returnMsg(textMessageDto));
    }

    public static void sendToAll(TextMessageDto textMessageDto){

        GlobalGroup.writeAndFlush(ReturnMsgUtil.returnMsg(textMessageDto));
    }

}
